package com.qianjiangcloud.store.activity.helpcentre;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.qianjiangcloud.store.libary.cache.MyImageLoader;

import com.qianjiangcloud.store.BaseDoFragment;
import com.qianjiangcloud.store.Run;
import com.qianjiangcloud.store.activity.AgentActivity;
import com.qianjiangcloud.store.http.JsonRequestBean;
import com.qianjiangcloud.store.http.JsonTask;
import com.qianjiangcloud.store.http.JsonTaskHandler;
import com.qianjiangcloud.store.ui.pulltorefresh.lib.PullToRefreshBase;
import com.qianjiangcloud.store.ui.pulltorefresh.lib.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import com.qianjiangcloud.store.R;

public class HelpCentreNewFragment extends BaseDoFragment {
    private PullToRefreshListView mListView;
    private List<JSONObject> schoolLists = new ArrayList<JSONObject>();
    private List<JSONObject> mParentLists = new ArrayList<JSONObject>();
    private HelpAdapter mAdapter;
    private int mPostion = 0;
    private String shareUrl;
    private String mId = "";
    private String mTotal = "";
    private int width;
    private boolean isLoadEnd;
    private boolean isLoadingData;
    private boolean isFrist = true;
    private JsonTask mTask;
    private boolean isScrolling;
//    public static String INITDATA="{\"rsp\":\"succ\",\"data\":[{\"article\":[{\"article_id\":\"47\",\"title\":\"\\u5546\\u54c1\\u9000\\u8d27\\u4fdd\\u969c\",\"platform\":\"pc\",\"type\":\"1\",\"node_id\":\"13\",\"author\":\"\",\"pubtime\":\"1285862400\",\"uptime\":\"1451376126\",\"level\":\"1\",\"ifpub\":\"true\",\"pv\":\"0\",\"disabled\":\"false\",\"sctype\":\"0\",\"image\":\"http:\\/\\/pic.shopex.cn\\/pictures\\/eimages\\/6e3e1e0ed4b3ad74130fd8acd7bcce985e95b2f346.gif?1451376148#h\",\"seo_description\":\"\",\"linkurl\":\"http:\\/\\/o2o-store.shopex123.com\\/beautiful_v1.4\\/index.php\\/wap\\/article-47.html\"},{\"article_id\":\"48\",\"title\":\"\\u79ef\\u5206\\u5956\\u52b1\\u8ba1\\u5212\",\"platform\":\"pc\",\"type\":\"1\",\"node_id\":\"13\",\"author\":\"\",\"pubtime\":\"1285862400\",\"uptime\":\"1451376126\",\"level\":\"1\",\"ifpub\":\"true\",\"pv\":\"0\",\"disabled\":\"false\",\"sctype\":\"0\",\"image\":\"http:\\/\\/pic.shopex.cn\\/pictures\\/eimages\\/6e3e1e0ed4b3ad74130fd8acd7bcce985e95b2f346.gif?1451376148#h\",\"seo_description\":\"\",\"linkurl\":\"http:\\/\\/o2o-store.shopex123.com\\/beautiful_v1.4\\/index.php\\/wap\\/article-48.html\"},{\"article_id\":\"49\",\"title\":\"\\u8ba2\\u5355\\u7684\\u51e0\\u79cd\\u72b6\\u6001\",\"platform\":\"pc\",\"type\":\"1\",\"node_id\":\"13\",\"author\":\"\",\"pubtime\":\"1285862400\",\"uptime\":\"1451376126\",\"level\":\"1\",\"ifpub\":\"true\",\"pv\":\"0\",\"disabled\":\"false\",\"sctype\":\"0\",\"image\":\"http:\\/\\/pic.shopex.cn\\/pictures\\/eimages\\/6e3e1e0ed4b3ad74130fd8acd7bcce985e95b2f346.gif?1451376148#h\",\"seo_description\":\"\",\"linkurl\":\"http:\\/\\/o2o-store.shopex123.com\\/beautiful_v1.4\\/index.php\\/wap\\/article-49.html\"},{\"article_id\":\"51\",\"title\":\"\\u987e\\u5ba2\\u5fc5\\u8bfb\",\"platform\":\"pc\",\"type\":\"1\",\"node_id\":\"13\",\"author\":\"\",\"pubtime\":\"1285862400\",\"uptime\":\"1451376126\",\"level\":\"1\",\"ifpub\":\"true\",\"pv\":\"0\",\"disabled\":\"false\",\"sctype\":\"0\",\"image\":\"http:\\/\\/pic.shopex.cn\\/pictures\\/eimages\\/6e3e1e0ed4b3ad74130fd8acd7bcce985e95b2f346.gif?1451376148#h\",\"seo_description\":\"\",\"linkurl\":\"http:\\/\\/o2o-store.shopex123.com\\/beautiful_v1.4\\/index.php\\/wap\\/article-51.html\"}],\"node_name\":\"\\u65b0\\u624b\\u4e0a\\u8def\"}],\"res\":\"\"}";
//    public static String REFRESHDATA="{    \"data\": [        {            \"article\": [                {                    \"article_id\": \"100\",                    \"author\": \"\",                    \"disabled\": \"false\",                    \"ifpub\": \"true\",                    \"image\": \"http://pic.shopex.cn/pictures/eimages/6e3e1e0ed4b3ad74130fd8acd7bcce985e95b2f346.gif?1451376148#h\",                    \"level\": \"1\",                    \"linkurl\": \"http://o2o-store.shopex123.com/beautiful_v1.4/index.php/wap/article-47.html\",                    \"node_id\": \"13\",                    \"platform\": \"pc\",                    \"pubtime\": \"1285862400\",                    \"pv\": \"0\",                    \"sctype\": \"0\",                    \"seo_description\": \"\",                    \"title\": \"啦啦啦啦啦拉拉啊\",                    \"type\": \"1\",                    \"uptime\": \"1451376126\"                },                {                    \"article_id\": \"48\",                    \"author\": \"\",                    \"disabled\": \"false\",                    \"ifpub\": \"true\",                    \"image\": \"http://pic.shopex.cn/pictures/eimages/6e3e1e0ed4b3ad74130fd8acd7bcce985e95b2f346.gif?1451376148#h\",                    \"level\": \"1\",                    \"linkurl\": \"http://o2o-store.shopex123.com/beautiful_v1.4/index.php/wap/article-48.html\",                    \"node_id\": \"13\",                    \"platform\": \"pc\",                    \"pubtime\": \"1285862400\",                    \"pv\": \"0\",                    \"sctype\": \"0\",                    \"seo_description\": \"\",                    \"title\": \"积分奖励计划\",                    \"type\": \"1\",                    \"uptime\": \"1451376126\"                },                {                    \"article_id\": \"49\",                    \"author\": \"\",                    \"disabled\": \"false\",                    \"ifpub\": \"true\",                    \"image\": \"http://pic.shopex.cn/pictures/eimages/6e3e1e0ed4b3ad74130fd8acd7bcce985e95b2f346.gif?1451376148#h\",                    \"level\": \"1\",                    \"linkurl\": \"http://o2o-store.shopex123.com/beautiful_v1.4/index.php/wap/article-49.html\",                    \"node_id\": \"13\",                    \"platform\": \"pc\",                    \"pubtime\": \"1285862400\",                    \"pv\": \"0\",                    \"sctype\": \"0\",                    \"seo_description\": \"\",                    \"title\": \"订单的几种状态\",                    \"type\": \"1\",                    \"uptime\": \"1451376126\"                },                {                    \"article_id\": \"51\",                    \"author\": \"\",                    \"disabled\": \"false\",                    \"ifpub\": \"true\",                    \"image\": \"http://pic.shopex.cn/pictures/eimages/6e3e1e0ed4b3ad74130fd8acd7bcce985e95b2f346.gif?1451376148#h\",                    \"level\": \"1\",                    \"linkurl\": \"http://o2o-store.shopex123.com/beautiful_v1.4/index.php/wap/article-51.html\",                    \"node_id\": \"13\",                    \"platform\": \"pc\",                    \"pubtime\": \"1285862400\",                    \"pv\": \"0\",                    \"sctype\": \"0\",                    \"seo_description\": \"\",                    \"title\": \"顾客必读\",                    \"type\": \"1\",                    \"uptime\": \"1451376126\"                }            ],            \"node_name\": \"新手上路\"        }    ],    \"res\": \"\",    \"rsp\": \"succ\"}";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActionBar.setShowHomeView(true);
        mActionBar.setTitle(R.string.me_item_help);
        mActionBar.setShowBackButton(true);
        WindowManager windowManager = mActivity.getWindowManager();
        width = (windowManager.getDefaultDisplay().getWidth()) / 4;
    }

    @Override
    public void init(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_help_centre_new, null);
        mListView = (PullToRefreshListView) findViewById(R.id.listview);
        mAdapter = new HelpAdapter();
        mListView.getRefreshableView().setAdapter(mAdapter);
        mListView.setPullToRefreshEnabled(true);
        mListView.setRefreshing();
        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {



            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    isScrolling = false;
                    //mGoodsListAdapter.notifyDataSetChanged();
                } else {
                    isScrolling = true;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (firstVisibleItem >= 2) {
                    rootView.findViewById(R.id.fragment_main_goto_top).setVisibility(View.VISIBLE);
                } else {
                    rootView.findViewById(R.id.fragment_main_goto_top).setVisibility(View.GONE);
                }
                if (totalItemCount < 3 || isLoadingData || isLoadEnd)
                    return;
                // 滚动到倒数第五个时，自动加载下一页
                if (totalItemCount - (firstVisibleItem + visibleItemCount) <= 1&&isScrolling) {
                    loadNextPage(mId);
                }
            }
        });

        mListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener() {
            @Override
            public void onRefresh() {
//                Run.excuteJsonTask(new JsonTask(), new GetHelpTask(""));
                loadRefreshPage();
            }

            @Override
            public void onRefreshMore() {

            }
        });
        loadRefreshPage();
//        Run.excuteJsonTask(new JsonTask(), new GetHelpTask(mId + 0));
    }

    //下拉刷新
    private void loadRefreshPage() {
        if (mTask != null && mTask.isExcuting)
            return;
        mTask = new JsonTask();
        schoolLists.clear();
        Run.excuteJsonTask(mTask, new GetHelpTask(""));
        mAdapter.notifyDataSetChanged();
    }

    private void loadNextPage(String mId) {
        if (mTask != null && mTask.isExcuting)
            return;
//        if (TextUtils.isEmpty(mId) && this.mId == mId) {
//            schoolLists.clear();
//            mAdapter.notifyDataSetChanged();
//            return;
//        }
//        else {
//            isFrist = false;
//            if (mTask != null && mTask.isExcuting)
//                return;
//        }

        if (mId == "null"&&isScrolling) {
//            Run.alert(getActivity(), "没有更多数据啦");
            return;
        } else {
            mTask = new JsonTask();
            Run.excuteJsonTask(mTask, new GetHelpTask(mId));
        }

    }

    class GetHelpTask implements JsonTaskHandler {
        private String typeID;

        public GetHelpTask(String ID) {
            this.typeID = ID;
        }

        @Override
        public void task_response(String json_str) {
//            TextUtils.isEmpty(String.valueOf(logId)) && this.logId == logId

            hideLoadingDialog_mt();
            mListView.onRefreshComplete();
            JSONObject all = null;//来判断这是一个滚动时候加载，还是直接去请求

            try {
//                JSONObject all = new JSONObject(INITDATA);
                all = new JSONObject(json_str);
                if (Run.checkRequestJson(mActivity, all)) {
                    JSONObject data = all.optJSONObject("data");
                    JSONArray artArray = data.getJSONArray("items");
                    mId = data.optString("last_id");
                    mTotal = data.optString("total");
                    if (artArray != null && artArray.length() > 0) {
                        for (int i = 0; i < artArray.length(); i++) {
                            schoolLists.add(artArray.getJSONObject(i));
                        }
                    }
//                    JSONArray array = all.getJSONArray("data");
//                    if (array != null && array.length() > 0) {
//                        JSONObject daJson = array.optJSONObject(0);
//                        if (daJson != null) {
//                            JSONArray artArray = daJson.optJSONArray("items");
//                            if (artArray != null && artArray.length() > 0) {
//                                for (int i = 0; i < artArray.length(); i++) {
//                                    schoolLists.add(artArray.getJSONObject(i));
//                                }
//                            }
//                        }
//                    }
                }
            } catch (Exception e) {
            } finally {
                mAdapter.notifyDataSetChanged();
            }
        }

        @Override
        public JsonRequestBean task_request() {
            if (!mListView.isRefreshing() && isFrist) {
                showCancelableLoadingDialog();
            }
            JsonRequestBean rb = new JsonRequestBean(
                    "mobileapi.helps.get_all_list");
            rb.addParams("last_id", typeID);
            return rb;
        }

    }

    class GetBarSchoolTask implements JsonTaskHandler {

        @Override
        public void task_response(String json_str) {
            hideLoadingDialog();
            try {
                JSONObject all = new JSONObject(json_str);
                if (Run.checkRequestJson(mActivity, all)) {
                    JSONObject dataJson = all.optJSONObject("data");
                    if (dataJson != null) {
//						JSONArray morenArray=dataJson.optJSONArray("moren");
//						if(morenArray!=null&&morenArray.length()>0){
//							JSONObject jsonLink=morenArray.optJSONObject(0);
//							if(jsonLink!=null){
//								jsonLink.optString("");
//							}
//
//						}
                        JSONArray nodeArray = dataJson.optJSONArray("node_id");
                        if (nodeArray != null && nodeArray.length() > 0) {
                            for (int i = 0; i < nodeArray.length(); i++) {
                                JSONObject jsonItem = nodeArray
                                        .optJSONObject(i);
                                if (jsonItem != null) {
                                    if (TextUtils.isEmpty(mId)) {
                                        mId = jsonItem.optString("node_id");
                                    }
                                    mParentLists.add(jsonItem);
                                }
                            }
                        }
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (mParentLists.size() > 0) {
                    Run.excuteJsonTask(new JsonTask(), new GetHelpTask(mId));
                }
            }

        }

        @Override
        public JsonRequestBean task_request() {
            if (!mListView.isRefreshing() && isFrist) {
                showCancelableLoadingDialog();
            }
            JsonRequestBean rb = new JsonRequestBean(
                    "mobileapi.article.get_sc_lists");
            return rb;
        }
    }


    public class HelpAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return schoolLists.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = getActivity().getLayoutInflater().inflate(
                        R.layout.item_school_view, null);
                holder = new ViewHolder();
                holder.tvTitle = (TextView) convertView
                        .findViewById(R.id.tv_title);
                holder.tvTime = (TextView) convertView
                        .findViewById(R.id.tv_time);
                holder.tvReadAll = (TextView) convertView
                        .findViewById(R.id.tv_read);
                holder.img = (ImageView) convertView
                        .findViewById(R.id.imageview);
                holder.seo_description = (TextView) convertView
                        .findViewById(R.id.seo_description);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            JSONObject object = schoolLists.get(position);
            holder.tvTime.setText(Run.getCurrentFormatedCurrenTime(Long
                    .parseLong(object.optString("pubtime"))));
            final String title = object.optString("title");
            holder.tvTitle.setText(title);
            holder.tvReadAll.setTag(object.optString("article_id"));
            holder.seo_description.setText(object.optString("seo_description"));
            final String nShareUrl = object.optString("linkurl");

          //  mImageLoader.showImage(holder.img, object.optString("image_id"));
            MyImageLoader.displayDefaultImage(object.optString("image_id"),holder.img);
            holder.tvReadAll.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    startActivity(AgentActivity
                            .intentForFragment(mActivity,
                                    AgentActivity.FRAGMENT_HELP_DETAIL)
                            .putExtra(Run.EXTRA_ARTICLE_ID,
                                    String.valueOf(v.getTag()))
                            .putExtra(Run.EXTRA_TITLE, title)
                            .putExtra(Run.EXTRA_DATA, nShareUrl));
                }
            });
            return convertView;
        }

        class ViewHolder {
            TextView tvTitle;
            TextView tvTime;
            TextView tvReadAll;
            ImageView img;
            TextView seo_description;
        }
    }
}
